package com.bjy.qa.service.project.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjy.qa.dao.functionaltest.TestSuiteDao;
import com.bjy.qa.dao.project.RobotDao;
import com.bjy.qa.entity.functionaltest.TestSuite;
import com.bjy.qa.entity.project.Robot;
import com.bjy.qa.exception.MyException;
import com.bjy.qa.service.project.IRobotService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class RobotService extends ServiceImpl<RobotDao, Robot> implements IRobotService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    RobotDao robotDao;

    @Resource
    TestSuiteDao testSuiteDao;

    @Override
    public Object listAll(Long projectId) {
        // 构造待查询 QueryWrapper
        QueryWrapper<Robot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId);
        queryWrapper.orderByDesc("id");
        return robotDao.selectList(queryWrapper);
    }

    @Override
    public Object add(Robot robot) {
        robotDao.insert(robot);
        return robot;
    }

    @Override
    public Object update(Robot robot) {
        // 更新数据需要清除 UpdatedTime，否则不会自动更新修改时间
        robot.setUpdatedAt(null);
        robot.setCreatedAt(null);

        robotDao.updateById(robot);

        return robot;
    }

    @Override
    public int delete(Long id) {
        QueryWrapper<TestSuite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("robot_id", id);
        queryWrapper.last("limit 1");
        if (testSuiteDao.selectList(queryWrapper).size() > 0) {
            throw new MyException("项目机器人删除失败，该机器人有测试套件在使用！");
        }

        return robotDao.deleteById(id);
    }
}
